package com.ny.dao.impl;

import com.ny.dao.OrderDao;
import com.ny.entity.Order;
import com.ny.until.DbUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    private DbUtil dbUtil = new DbUtil();
    @Override
    public int insertOrder(Order order) throws SQLException {
        Connection connection = dbUtil.getCon();
        String sql = "INSERT INTO orders(student_id, product_id, number, total_price) VALUES (?, ?, ?, ?)";
        try (Connection conn = dbUtil.getCon();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, order.getStudentId());
            ps.setInt(2, order.getProductId());
            ps.setInt(3, order.getNumber());
            ps.setDouble(4, order.getTotalPrice());

            return ps.executeUpdate();
        }
    }

    @Override
    public List<Order> selectAllOrders() throws SQLException {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders";
        try (Connection conn = dbUtil.getCon();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                Order order = new Order();
                order.setOrderId(rs.getInt("order_id"));
                order.setStudentId(rs.getInt("student_id"));
                order.setProductId(rs.getInt("product_id"));
                order.setNumber(rs.getInt("number"));
                order.setTotalPrice(rs.getDouble("total_price"));
                orders.add(order);
            }
        }
        return orders;
    }

    @Override
    public int deleteOrder(int orderId) throws SQLException {
        String sql = "DELETE FROM orders WHERE order_id = ?";
        try (Connection conn = dbUtil.getCon();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, orderId);
            return ps.executeUpdate();
        }
    }
}


